package com.hrm.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hrm.config.JSPPage;
import com.hrm.config.MsgType;
import com.hrm.entity.ConfigItem;
import com.hrm.entity.Message;
import com.hrm.entity.Config;
import com.hrm.entity.User;
import com.hrm.service.ConfigService;
import com.hrm.service.UserLogService;
import com.hrm.util.DateUtil;
import com.hrm.util.JSONUtil;
import com.hrm.util.Page;


@Controller
@RequestMapping("/config.do")
public class ConfigAction {
	private static final Log log = LogFactory.getLog(ConfigAction.class); 
	@Autowired
	private ConfigService configService;
	@Autowired
	private UserLogService userLogService;
	
	public UserLogService getUserLogService() {
		return userLogService;
	}
	public void setUserLogService(UserLogService userLogService) {
		this.userLogService = userLogService;
	}
	public ConfigService getConfigService() {
		return configService;
	}
	public void setConfigService(ConfigService configService) {
		this.configService = configService;
	}
	@RequestMapping(params = "method=getConfigs")
	public String getConfigs(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		//获取所有数据的前15条数据
		Page page = new Page();
		page.setPagesize(Integer.parseInt(request.getParameter("rows")));
		page.setCurrentpage(Integer.parseInt(request.getParameter("page")));
		Map<String, Object> searchMap = new HashMap<String, Object>();
		if("true".equals(request.getParameter("_search"))){
			searchMap.put(request.getParameter("searchField"),request.getParameter("searchString"));
		}
		List<Config> configs = configService.getConfigs(page);
		page.setCounts(configService.getConfigCounts());
		if(configs!=null){
			log.info("begin to getConfigs");
			try {
				Map<String, Object> resultMap2 = new HashMap<String, Object>();
				resultMap2.put("page", page.getCurrentpage()+"");
				log.debug("currentpage="+page.getCurrentpage());
				log.debug("countpage="+page.getCountPage());
				log.debug("records="+page.getCounts());
				resultMap2.put("total", page.getCountPage()+"");
				resultMap2.put("records", page.getCounts()+"");
				List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
				for(Config u:configs){
					Map<String, Object> rowMap =new HashMap<String, Object>();
					rowMap.put("id", u.getId());
					List<String> list = new ArrayList<String>();
					list.add(u.getId()+"");
					//配置实现表格超链接
					list.add("<a href='javascript:void(0)' class='configManageLink' name='"+u.getCode()+"'>"+u.getCode()+"</a>");
					list.add(u.getName()+"");
					list.add(u.getUserName()+"");
					list.add(DateUtil.formate(u.getUpdateTime())+"");
					list.add(u.getRemark());
					rowMap.put("cell", list);
					rows.add(rowMap);
				}
				resultMap2.put("rows", rows);
				String result=JSONUtil.parseMap(resultMap2);
				response.getWriter().print(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				Message message = new Message("ERROR", "获取数据失败或数据为空!", new Date());
				System.out.println(message.toJSONString());
				response.getWriter().print(message.toJSONString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=getConfigItems")
	public String getConfigItems(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		//获取所有数据的前15条数据
		Page page = new Page();
		page.setPagesize(Integer.parseInt(request.getParameter("rows")));
		page.setCurrentpage(Integer.parseInt(request.getParameter("page")));
		Map<String, Object> searchMap = new HashMap<String, Object>();
		if("true".equals(request.getParameter("_search"))){
			searchMap.put(request.getParameter("searchField"),request.getParameter("searchString"));
		}
		String type=request.getParameter("type")==null?"":request.getParameter("type");
		if("".equals(type.trim())){
			Message message = new Message();
			message.setMsg("必须传入配置项编码!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		List<ConfigItem> configItems = configService.getConfigItemsByType(page,type);
		page.setCounts(configService.getConfigItemsCountsByType(type));
		if(configItems!=null){
			log.info("begin to getConfigs");
			try {
				Map<String, Object> resultMap2 = new HashMap<String, Object>();
				resultMap2.put("page", page.getCurrentpage()+"");
				log.debug("currentpage="+page.getCurrentpage());
				log.debug("countpage="+page.getCountPage());
				log.debug("records="+page.getCounts());
				resultMap2.put("total", page.getCountPage()+"");
				resultMap2.put("records", page.getCounts()+"");
				List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
				for(ConfigItem u:configItems){
					Map<String, Object> rowMap =new HashMap<String, Object>();
					rowMap.put("id", u.getId());
					List<String> list = new ArrayList<String>();
					list.add(u.getId()+"");
					//配置实现表格超链接
					list.add(u.getConfigCode()+"");
					list.add(u.getConfigName()+"");
					list.add(u.getConfigType()+"");
					list.add(u.getRemark());
					rowMap.put("cell", list);
					rows.add(rowMap);
				}
				resultMap2.put("rows", rows);
				String result=JSONUtil.parseMap(resultMap2);
				response.getWriter().print(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				Message message = new Message("ERROR", "获取数据失败或数据为空!", new Date());
				System.out.println(message.toJSONString());
				response.getWriter().print(message.toJSONString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=getConfigItemsByConfigType")
	public String getConfigItemsByConfigType(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		String type=request.getParameter("type")==null?"":request.getParameter("type");
		if("".equals(type.trim())){
			Message message = new Message();
			message.setMsg("必须传入配置项类型!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		List<ConfigItem> configItems = configService.getConfigItemsByType(type);
		if(configItems!=null){
			try {
				String result=JSONUtil.parseList(configItems);
				response.getWriter().print(result);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				Message message = new Message("ERROR", "获取数据失败或数据为空!", new Date());
				response.getWriter().print(message.toJSONString());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=addConfig")
	public String addConfig(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		Message message = new Message();
		String name=request.getParameter("name")==null?"":request.getParameter("name");
		String code=request.getParameter("code")==null?"":request.getParameter("code");
		String remark=request.getParameter("remark")==null?"":request.getParameter("remark");
		if("".equals(name)||name.getBytes().length>=50){
			message.setMsg("配置项名不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if("".equals(code)||code.getBytes().length>=20){
			message.setMsg("配置项编码不能为空且长度必须在20个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(remark.getBytes().length>=200){
			message.setMsg("备注长度必须在200个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Config config = new Config();
		config.setName(name);
		config.setCode(code);
		config.setUpdateTime(new Date());
		config.setRemark(remark);
		User user = (User) request.getSession().getAttribute("user");
		config.setUserName(user.getUserName());
		config.setUserId(user.getId());
		if(configService.addConfig(config)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("新增配置项成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_CONFIG, "添加配置项:"+name,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=addConfigItem")
	public String addConfigItem(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		Message message = new Message();
		String configName=request.getParameter("configName")==null?"":request.getParameter("configName");
		String configCode=request.getParameter("configCode")==null?"":request.getParameter("configCode");
		String configType=request.getParameter("configType")==null?"":request.getParameter("configType");
		String remark=request.getParameter("remark")==null?"":request.getParameter("remark");
		if("".equals(configName)||configName.getBytes().length>=50){
			message.setMsg("代码名称不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if("".equals(configCode)||configCode.getBytes().length>=50){
			message.setMsg("代码值不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if("".equals(configType)||configType.getBytes().length>=50){
			message.setMsg("所属配置项不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(remark.getBytes().length>=200){
			message.setMsg("备注长度必须在200个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		ConfigItem configItem = new ConfigItem();
		configItem.setConfigCode(configCode);
		configItem.setConfigName(configName);
		configItem.setConfigType(configType);
		configItem.setRemark(remark);
		if(configService.addConfigItem(configItem)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("新增代码项成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_CONFIG, "新增代码:代码名称"+configName+",所属配置项"+configType,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=updateConfig")
	public String updateConfig(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id"));
		Config config = configService.getConfigById(id);
		if(config==null){
			Message message = new Message();
			message.setMsg("获取配置项信息失败!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		map.put("config", config);
		return JSPPage.CONFIG_EDIT;
	}
	@RequestMapping(params = "method=updateConfigItem")
	public String updateConfigItem(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id"));
		ConfigItem configitem = configService.getConfigItemById(id);
		if(configitem==null){
			Message message = new Message();
			message.setMsg("获取代码信息失败!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		map.put("configItem", configitem);
		return JSPPage.CONFIG_ITEM_EDIT;
	}
	@RequestMapping(params = "method=updateConfigById")
	public String updateConfigById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		if(id==-1){
			Message message = new Message();
			message.setMsg("必须传入配置项ID才能编辑!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String name=request.getParameter("name")==null?"":request.getParameter("name");
		String code=request.getParameter("code")==null?"":request.getParameter("code");
		String remark=request.getParameter("remark")==null?"":request.getParameter("remark");
		Message message = new Message();
		if("".equals(name)||name.getBytes().length>=20){
			message.setMsg("配置项名不能为空且长度必须在20个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if("".equals(name)||name.getBytes().length>=50){
			message.setMsg("配置项名不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if("".equals(code)||code.getBytes().length>=20){
			message.setMsg("配置项编码不能为空且长度必须在20个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(remark.getBytes().length>=200){
			message.setMsg("备注长度必须在200个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Config config = configService.getConfigById(id);
		//修改配置项编码时同时修改其代码项对应的配置项类型
		List<ConfigItem> configItems = configService.getConfigItemsByType(config.getCode());
		for (ConfigItem configItem : configItems) {
			configItem.setConfigType(code);
			configService.updateConfigItem(configItem);
		}
		config.setName(name);
		config.setCode(code);
		config.setRemark(remark);
		config.setUpdateTime(new Date());
		User user =(User) request.getSession().getAttribute("user");
		config.setUserId(user.getId());
		config.setUserName(user.getUserName());
		if(configService.updateConfig(config)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("编辑配置项成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_CONFIG, "编辑配置项:"+name,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=updateConfigItemById")
	public String updateConfigItemById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		if(id==-1){
			Message message = new Message();
			message.setMsg("必须传入代码ID才能编辑!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String configName=request.getParameter("configName")==null?"":request.getParameter("configName");
		String configCode=request.getParameter("configCode")==null?"":request.getParameter("configCode");
		String remark=request.getParameter("remark")==null?"":request.getParameter("remark");
		Message message = new Message();
		if("".equals(configName)||configName.getBytes().length>=50){
			message.setMsg("代码名称不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if("".equals(configCode)||configCode.getBytes().length>=50){
			message.setMsg("代码值不能为空且长度必须在50个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(remark.getBytes().length>=200){
			message.setMsg("备注长度必须在200个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		ConfigItem configItem = configService.getConfigItemById(id);
		configItem.setConfigName(configName);
		configItem.setConfigCode(configCode);
		configItem.setRemark(remark);
		if(configService.updateConfigItem(configItem)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("编辑代码成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_CONFIG, "编辑代码:代码名称"+configName+",所属配置项"+configItem.getConfigType(),userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=deleteConfigById")
	public String deleteConfigById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		String configids = request.getParameter("configids")==null?"":request.getParameter("configids");
		Message message = new Message();
		if("".equals(configids)){
			message.setMsg("必须传入配置项ID才能删除!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(configService.deleteConfigById(configids)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("删除配置项成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_CONFIG, "删除配置项:删除的配置项Id为"+configids,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=deleteConfigItemById")
	public String deleteConfigItemById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		String configItemids = request.getParameter("configItemids")==null?"":request.getParameter("configItemids");
		Message message = new Message();
		if("".equals(configItemids)){
			message.setMsg("必须传入代码ID才能删除!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(configService.deleteConfigItemById(configItemids)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("删除代码成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_CONFIG, "删除代码:代码id为"+configItemids,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
}
